import React from 'react';
import { TreeSelect, Tooltip } from 'antd';
import { PlusCircleOutlined } from '@ant-design/icons';

const { TreeNode } = TreeSelect;

const SearchTree = {
  transData: (values, name) => values[name],
  render: (item, onChange) => {
    const { items = [], value = [], multiples } = item;

    const appendChange = (selectedValues) => {
      onChange({ [item.name]: Array.from(new Set([...value, ...selectedValues])) }, item.name);
    };

    const getChildsValue = (aItem, aInitNode) => {
      if (!aItem || aItem.length === 0) {
        return;
      }
      aItem.map((subItem) => {
        aInitNode.push(subItem.value);
        getChildsValue(subItem.children, aInitNode);
      });
    };

    const handleLineContainChildsClick = (e, node) => {
      e.stopPropagation();
      const selectedValues = [node.value];
      getChildsValue(node.children, selectedValues);
      appendChange(selectedValues); // ???
    };

    const renderTreeNode = (treeData = []) =>
      treeData.map((node) => {
        if (!node.children || node.children.length < 1) {
          return <TreeNode value={node.value} title={node.label} key={node.value} />;
        }

        const iconEle = (
          <div className="container-childs" title={node.label}>
            {multiples && (
              <span
                onClick={(e) => {
                  handleLineContainChildsClick(e, node);
                }}
              >
                <Tooltip title="选择该部门及其子部门">
                  <PlusCircleOutlined />
                </Tooltip>
              </span>
            )}
            {node.label}
          </div>
        );
        return (
          <TreeNode value={node.value} title={iconEle} key={node.value}>
            {renderTreeNode(node.children)}
          </TreeNode>
        );
      });

    return (
      <TreeSelect
        className="search-form-item"
        value={value}
        dropdownStyle={{ maxHeight: 500, overflow: 'auto' }}
        showSearch
        multiple={multiples === true}
        treeDefaultExpandAll
        maxTagCount={200}
        placeholder="请选择"
        allowClear
        treeNodeFilterProp="label"
        onChange={(val) => onChange({ [item.name]: val }, item.name)}
      >
        {renderTreeNode(items)}
      </TreeSelect>
    );
  },
};

export default SearchTree;
